<?php

namespace app\service;

use app\model\AccountManage;
use app\model\Company;
use app\model\Driver;
use app\model\DriverClockModel;
use app\model\DriverModel;
use app\model\Group;
use app\model\PartnerLogModel;
use app\model\PartnerUser;
use app\model\WarehouseModel;
use app\model\AccountBankModel;
use app\model\AccountManageModel;
use app\model\TaskModel;
use app\model\DeliveryOrderModel;
use app\utils\Md5Service;
use think\facade\Db;

class DriverService
{
    public static function attendance_lists($param)
    {
        $list = DriverModel::lists($param);
        if (!isset($param['date'])) {
            $month = getNowMonth();
        } else {
            $month = getAppointMonth(strtotime($param['date']));
        }
        foreach ($list as $k => $v) {
            $attendance_list = DriverModel::attendance_date(['partner_id' => $param['partner_id'], 'driver_id' => $v['id']], $month);
            $list[$k]['attendance_list'] = $attendance_list;
        }
        return $list;
    }

    public static function lists($param)
    {
        $lists = DriverModel::lists($param);

        foreach ($lists['list'] as $key => $value) {
            $recordsBank = AccountBankModel::getListsByUid($value['id'], 1);
            $lists['list'][$key]['bank_count'] = count($recordsBank);
            $lists['list'][$key]['bank_list'] = $recordsBank;
        }

        return $lists;
    }

    public static function line_data($param)
    {
        return DriverModel::line_data($param);
    }

    public static function info()
    {
        $warehouseType = WarehouseModel::GetAllWarehouseType();
        $bussineType = WarehouseModel::GetAllBussineType();
        return [
            'warehouseType' => $warehouseType,
            'bussineType' => $bussineType
        ];
    }

    public static function add($data, $logParam)
    {
        Db::startTrans();
        $data['salt'] = GetRandStr(10);
        $data['api_salt'] = GetRandStr(10);
        $data['no'] = "D" . GetRandInt(10);
        $data['add_time'] = getNowDateTime();
        $data['login_pass'] = 123456;
        $data['login_pass'] = Md5Service::encryptMd5($data['login_pass'], $data['salt']);
        $res = DriverModel::add($data);

        $dataAccount['company_id'] = $data['company_id'];
        $dataAccount['account_no'] = "ZH" . getDay() . GetRandInt(8);
        $dataAccount['type'] = 1;
        $dataAccount['user_id'] = $res;
        $dataAccount['status'] = 1;
        $dataAccount['add_time'] = getNowDateTime();
        $resAccountId = AccountManageModel::add($dataAccount);
        //添加数据权限
        $uid = getUid($res, $data['company_id'],$data['department_id']);
        $DriverUP= Driver::where('id',$res)->update(['uid'=>$uid]);
        $AccountManageUP =AccountManage::where('id',$resAccountId)->update(['uid'=>$uid]);

        if (empty($resAccountId)||!$DriverUP||!$AccountManageUP) {
            Db::rollback();
            return 10003;
        }

        $dataLog = [
            'partner_user_id' => $logParam['uid'],
            'log_type' => 2,
            'request_ip' => $logParam['ip'],
            'add_time' => getNowDateTime(),
            'log_desc' => '添加司机',
            'status' => 1,
            'partner_id' => $data['partner_id']
        ];
        
        if ($res ) {
            Db::commit();
            return 10000;
        } else {
            // 回滚事务
            Db::rollback();
            return 10003;
        }
    }

    public static function edit($data, $logParam, $id)
    {
        Db::startTrans();
        $data['salt'] = GetRandStr(10);
        $data['api_salt'] = GetRandStr(10);
        $data['login_pass'] = Md5Service::encryptMd5($data['login_pass'], $data['salt']);
        $res = DriverModel::edit($data, $id);
        $dataLog = [
            'partner_user_id' => $logParam['uid'],
            'log_type' => 2,
            'request_ip' => $logParam['ip'],
            'add_time' => getNowDateTime(),
            'log_desc' => '修改司机信息',
            'status' => 1,
            'partner_id' => $data['partner_id']
        ];
        

        //添加数据权限
        $uid = getUid($res, $data['company_id'],$data['department_id']);
        $DriverUP= Driver::where('id',$id)->update(['uid'=>$uid]);
        $AccountManageUP =AccountManage::where('user_id',$id)->where('type',1)->update(['uid'=>$uid]);

        if ($res ) {
            Db::commit();
            return 10000;
        } else {
            // 回滚事务
            Db::rollback();
            return 10003;
        }
    }

    public static function del($data, $logParam, $id)
    {
        Db::startTrans();
        $res = DriverModel::del($id);
        $dataLog = [
            'partner_user_id' => $logParam['uid'],
            'log_type' => 2,
            'request_ip' => $logParam['ip'],
            'add_time' => getNowDateTime(),
            'log_desc' => '删除司机信息',
            'status' => 1,
            'partner_id' => $data['partner_id']
        ];
        
        if ($res ) {
            Db::commit();
            return 10000;
        } else {
            // 回滚事务
            Db::rollback();
            return 10003;
        }
    }

    public static function workRecode($param)
    {
        $list = DriverClockModel::lists($param);
        if (!empty($list['list'])) {
            foreach ($list['list'] as $k => $v) {
                //任务状态
                $list['list'][$k]['task_status'] = self::getTaskStatus($v);
                if ($v['ring_status'] == 2) {
                    //耗时
                    $list['list'][$k]['diff_time'] = timediff($v['add_time'], $v['down_time']);
                    //系统里程数
                    $list['list'][$k]['s_mileage'] = self::getSMileage($v);
                    //实际里程数
                    $list['list'][$k]['r_mileage'] = bcsub($v['d_mileage'], $v['u_mileage'], 2);
                } else {
                    $list['list'][$k]['diff_time'] = "";
                    //系统里程数
                    $list['list'][$k]['s_mileage'] = "";
                    //实际里程数
                    $list['list'][$k]['r_mileage'] = "";
                }
            }
        }
        return $list;
    }

    public static function income_lists($param)
    {
        $retList = [];
        $currentKey = 0;
        $param['task_type'] = 2;
        $taskList = TaskModel::lists($param);
        // dump($list);exit;
        if (empty($taskList['list'])) {
            return [];
        }
        foreach ($taskList['list'] as $k => $v) {
            //任务状态
            $taskList['list'][$k]['task_status'] = self::getTaskStatus($v);
            $filter['driver_id'] = $param['driver_id'];
            $filter['tms_task_id'] = $v['id'];
            $filter['datestr'] = date('Y-m-d', (strtotime($v['date']) - 60*60*24));
            $filter['network_ids'] = $v['network_ids'];
            $filter['page'] = 1;
            $filter['limit'] = 100;
            $deliveryOrders = DeliveryOrderModel::lists($filter);
            $orderOutIds = ''; 
            foreach ($deliveryOrders['lists'] as $kdo => $vdo) {
                if ($orderOutIds) {
                    if ($vdo['link_order_ids']) {
                        $orderOutIds = $orderOutIds . ',' . $vdo['link_order_ids'];
                    }
                }else{
                    if ($vdo['link_order_ids']) {
                        $orderOutIds = $vdo['link_order_ids'];
                    }                    
                }
            }
            $taskList['list'][$k]['income_total'] = 0.00;
            if (empty($orderOutIds)) {
                continue;
            }
            $orderOutRecords = Db::table('xl_purchase_orderout')->where('id', 'IN', $orderOutIds)->select()->toArray();
            if (empty($orderOutRecords)) {
                continue;
            }
            foreach ($orderOutRecords as $koor => $voor) {
                $retList[$currentKey]['task_time'] = $v['date'];
                $retList[$currentKey]['task_no'] = $v['no'];
                $retList[$currentKey]['driver_commission'] = $voor['driver_commission'];
                $retList[$currentKey]['ship_address'] = Db::table('xl_warehouse')->where('id','=', $vdo['warehouse_id'])->value('name');
                $retList[$currentKey]['receiver_address'] = Db::table('xl_networks')->where('id','=', $vdo['network_id'])->value('receiver_address');
                $retList[$currentKey]['delivery_status'] = $vdo['delivery_status'];
                $retList[$currentKey]['driver_name'] = Db::table('xl_driver')->where('id','=', $vdo['driver_id'])->value('name');
                $retList[$currentKey]['delivery_get_time'] = $vdo['start_time'];
                $retList[$currentKey]['delivery_done_time'] = $vdo['delivery_time'];
                $retList[$currentKey]['consume_time'] = ceil((strtotime($vdo['delivery_time']) - strtotime($vdo['start_time'])) / 60);

                $retList[$currentKey]['settlement_status'] = 1;
                if ($voor['channel_order_id']) {
                    $where[] = [];
                    $where[] = ['order_id', '=', $voor['channel_order_id']];
                    $where[] = ['type', '=', 2];
                    $retList[$currentKey]['settlement_status'] = Db::table('xl_bill_note')->where($where)->value('settlement_status');;
                }
                $currentKey++;
            }

            // $taskList['list'][$k]['income_total'] = array_sum(array_filter(array_column($orderOutRecords, 'driver_commission')));
        }
        return $retList;
    }

    public static function getSMileage($info)
    {
        $url = 'http://gpstime.xianlian.cc/api/mileage';
        $gpsMobile = Db::table('xl_cars')->where('id', $info['car_id'])->value('gps_mobile');
        $carNumber = Db::table('xl_cars')->where('id', $info['car_id'])->value('car_plate_number');
        $basicPost = https_request_one($url, ['mobile' => stripslashes($gpsMobile), 'car_number' => stripslashes($carNumber), 's_time' => stripslashes($info['add_time']), 'e_time' => stripslashes($info['down_time'])]);
        $basicPost = json_decode($basicPost, true);
        if ($basicPost['code'] == 200) {
            $millageLength = round($basicPost['data']['millage_length'], 2);
        } else {
            $millageLength = '暂未查询到-0';
        }
        return $millageLength;
    }

    public static function getTaskStatus($info)
    {
        $subStr = substr($info['date'], 0, 10);
        $taskStatus = Db::table('xl_normal_task')->where('car_id', $info['car_id'])->where('date', $subStr)->column('task_status');
        $uniStatus = array_unique($taskStatus);
        if (count($uniStatus) == 1 && $uniStatus[0] == 4) {
            return 1;
        }
        if (in_array(5, $taskStatus)) {
            return 2;
        }
        return 3;
    }
}